package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	"ruikc.com/server/utils"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type NewsSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNewsSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewsSaveLogic {
	return &NewsSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NewsSaveLogic) NewsSave(req *types.NewsReq) (resp string, err error) {
	category := &models.Category{Id: req.Cid}
	has := db.ExistData(category)
	if !has {
		return "", errors.New("新闻分类不存在")
	}
	data := &models.News{}
	copier.Copy(data, req)

	if data.PublishedAt == "" {
		data.PublishedAt = utils.NowDate(utils.TimeFormat)
	}

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		db.UpdateData(data, xb.Eq{"id": req.Id})
	}

	return "操作成功", nil
}
